const Service = require("egg").Service;
// const fs = require("fs");
// const path = require("path");
// const awaitWriteStream = require("await-stream-ready").write;
// const sendToWormhole = require("stream-wormhole");
// const uuid = require("uuid");

const path = require('path');
const fs = require('fs');
const mkdirp = require('mkdirp');
const moment = require('moment');
const uuid = require('uuid');
const awaitStreamReady = require('await-stream-ready').write;


function getDate () {
  var nowDate = new Date();
  var year = nowDate.getFullYear();
  var month = nowDate.getMonth() + 1 < 10 ? "0" + (nowDate.getMonth() + 1) : nowDate.getMonth() + 1;
  var day = nowDate.getDate() < 10 ? "0" + nowDate.getDate() : nowDate.getDate();
  var dateStr = `${year}-${month}-${day}`;
  return dateStr;
}

/**
 * 判读路径是否存在,如不存在创建文件夹
 * @param pathStr 参数要用path.join()拼接,项目下的相对路径
 * @return projectPath 返回绝对路径,可要可不要
 */
function mkdirPath (pathStr) {
  var projectPath = path.join(process.cwd());
  var tempDirArray = pathStr.split('\\');

  for (var i = 0; i < tempDirArray.length; i++) {
    projectPath = projectPath + '/' + tempDirArray[i];
    if (fs.existsSync(projectPath)) {
      var tempstats = fs.statSync(projectPath);
      if (!(tempstats.isDirectory())) {
        fs.unlinkSync(projectPath);
        fs.mkdirSync(projectPath);
      }
    }
    else {
      fs.mkdirSync(projectPath);
    }
  }
  return projectPath;
}


class sUploadFile extends Service {
  async uploadFiles () {
    const { ctx } = this;
    console.log("======================="); 
    const stream = await ctx.getFileStream();
    console.log("=======================");
    const basePath = path.resolve(__dirname, '../public/upload', moment().format('YYYYMMDD'));
    await mkdirp(basePath); // 生成本地对应文件夹
    const filename = uuid.v1() + path.extname(stream.filename).toLocaleLowerCase();
    const localFilePath = path.resolve(basePath, filename);
    const writeStream = fs.createWriteStream(localFilePath);
    let url = "";
    try {
      // 暂停流，防止内存泄漏
      await awaitStreamReady(stream.pipe(writeStream));
      url = '/public/upload/' + moment().format('YYYYMMDD') + '/' + filename;
    } catch (err) {
      await sendToWormhole(stream);
      url = '';
    }
    return url;
  }
}
module.exports = sUploadFile;
